# flask web 网络编程文件
from flask import Flask, render_template, request,escape
from vsearch import search4letters
from geo import geocode
from geo import cycle
# html 调用方法：render_template  按照 jinja2 规则
def log_request(req: 'flask_request',res: str) -> None:
    with open('huang_rizhi.py','a')as log:
        # print(req.form,file=log,end="|")
        # print(req.remote_addr,file=log,end="|")
        # print(req.user_agent,file=log,end="|")
        print(req.form, req.remote_addr,req.user_agent,res,file=log,sep=" | ")
# print(str(dir(req)),res,file=log)
xiaomo_key='9ad72c62215d7263682b408f01926df8'
app = Flask(__name__)


@app.route('/search4', methods=['POST'])
# 这些数据来自哪里？
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    color=request.form['color']
    color01 = request.form['color01']

    用户输入的结构化地址=request.form['geocode']
    经纬度坐标=geocode(xiaomo_key,用户输入的结构化地址)
    origin03 = request.form['origin5']
    origin=geocode(xiaomo_key,origin03)
    destination2 = request.form["destination5"]
    destination3 =geocode(xiaomo_key,destination2)
    骑行规划 = cycle(xiaomo_key,origin,destination3)
    title = 'Here are your results:'
    results = str(search4letters(phrase, letters))
    log_request(request,results)
    # with open('huang_rizhi.py','a')as f:
    #     print(request,results,file=f)
    return render_template('results.html',
                           the_title=title,
                           the_phrase=phrase,
                           the_letters=letters,
                           the_results=results,
                           the_color=color,
                           the_color01=color01,
                           the_geo=经纬度坐标,
                           the_cycle=骑行规划,)


@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    title = '欢迎来测试xiaomo的珍珠奶茶有没有珍珠'
    return render_template('entry.html',
                           the_title=title)


@app.route("/login",methods=['get'])
def index()-> 'html':
    title ='welcome'
    return render_template("login.html",the_title=title)


@app.route("/person",methods=["POST"])
def person():
    image_url=request.form["person"]
    subscription_key = "7388368827d942c5b517d8c6218ef191"
    assert subscription_key
    vision_base_url = "https://cvhzx.cognitiveservices.azure.com/vision/v2.1/"
    celebrity_analyze_url = vision_base_url + "models/celebrities/analyze"
    headers = {'Ocp-Apim-Subscription-Key': subscription_key}
    params = {'model': 'celebrities'}
    data = {'url': image_url}
    response = requests.post(celebrity_analyze_url, headers=headers, params=params, json=data)
    response.raise_for_status()
    analysis = response.json()
    celebrity_name = analysis["result"]["celebrities"][0]["name"].capitalize()
    confidence2=analysis["result"]["celebrities"][0]["confidence"]
    return render_template('entry.html',person=str(celebrity_name),confidence2=str(confidence2),img_url3=image_url)



if __name__ == '__main__':
    app.run(debug=True)
# from flask import escape
# escape('this is a Request')
# with open('huang_rizhi.py','a')as log:
#     contents = log.readlines()
# return escape('',join(contents))



@app.route('/viewlog')
def view_the_log() -> 'html':
    contents = []
    with open('huang_rizhi.py') as log:
        for line in log:
            contents.append([])
            for item in line.split(' | '):
                contents[-1].append(escape(item))
    titles = ('Form Data','Remote_addr', 'User_agent', 'Results')
    return render_template('viewlog.html',
                           the_title='huang_rizhi',
                           the_row_titles=titles,
                           the_data=contents,)
